package com.eleadmin.order.biz.impl;

import com.eleadmin.damon.utils.constant.UserConstant;
import com.eleadmin.damon.utils.results.BaseDao;
import com.eleadmin.damon.utils.results.PageResult2;
import com.eleadmin.damon.utils.utils.DateUtil;
import com.eleadmin.damon.utils.utils.Utils;
import com.eleadmin.order.biz.UserBiz2;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.common.core.web.JsonResult;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

/**
 *
 * 数据层实现类
 * @author : Doman
 * @date : 2023-04-21 10:42:44
 * @version ：1.0
 */
@Repository
public class UserBizImpl2 extends BaseDao implements UserBiz2 {

    @Override
    public JsonResult list(PageResult2<T> page, User user, User loginUser) throws Exception {
        Map<String, String> map  = new HashMap<String, String>();
        RowMapper<User> rm = new BeanPropertyRowMapper<User>(User.class);
        StringBuffer sql = new StringBuffer("select u.user_id,u.username,u.password");
        sql.append(",u.nickname,u.avatar,u.sex,u.phone");
		sql.append(",u.email,u.email_verified,u.real_name,u.id_card");
		sql.append(",u.birthday,u.introduction,u.organization_id,u.status");
		sql.append(",u.tenant_id,u.type,u.admin,u.state");
		sql.append(",u.customer_id,u.gzhId,u.create_time,u.create_user");
		sql.append(",u.update_time,u.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nickname createName,suser2.nickname updateName ");
        sql.append(" from sys_user u ");
        sql.append(" inner join sys_user suser on suser.user_id=u.create_user ");
        sql.append(" left join sys_user suser2 on suser2.user_id=u.update_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=u.organization_id and sogzn.deleted=0 ");
        sql.append(" where u.deleted=0 ");
        if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and u.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
        if(Utils.isNotEmpty(user)){
    //			if(Utils.isNotEmpty(user.getName())){
    //				sql.append(" and instr(u.name,:name)>0 ");
    //				map.put("name", user.getName());
    //			}
//            if(Utils.isNotEmpty(user.getSort())&&Utils.isNotEmpty(user.getOrder())){
//                sql.append(" order by u."+user.getSort()+" "+user.getOrder());
//            } else {
//                sql.append(" order by u.create_time desc");
//            }
        }
        return jsonResult(getPageQueryList(page, sql.toString(), map, rm));
    }

    @Override
    public List<User> list(User user, User loginUser) {
        Map<String, String> map  = new HashMap<String, String>();
        RowMapper<User> rm = new BeanPropertyRowMapper<User>(User.class);
        StringBuffer sql = new StringBuffer("select u.user_id,u.username,u.password");
        sql.append(",u.nickname,u.avatar,u.sex,u.phone");
		sql.append(",u.email,u.email_verified,u.real_name,u.id_card");
		sql.append(",u.birthday,u.introduction,u.organization_id,u.status");
		sql.append(",u.tenant_id,u.type,u.admin,u.state");
		sql.append(",u.customer_id,u.gzhId,u.create_time,u.create_user");
		sql.append(",u.update_time,u.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nickname createName ");
        sql.append(" from sys_user u ");
        sql.append(" inner join sys_user suser on suser.user_id=u.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=u.organization_id and sogzn.deleted=0 ");
        sql.append(" where u.deleted=0 ");
        if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and u.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
//        if(Utils.isNotEmpty(user)){
//            if(Utils.isNotEmpty(user.getSort())&&Utils.isNotEmpty(user.getOrder())){
//                sql.append(" order by u."+user.getSort()+" "+user.getOrder());
//            } else {
//                sql.append(" order by u.create_time desc");
//            }
//        }
        getMapParameter(sql, map);
        return jdbcTemplate.query(sql.toString(),map, rm);
    }

    @Override
    public User getById(String id) {
        RowMapper<User> rm = new BeanPropertyRowMapper<User>(User.class);
        Map<String, String> map  = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("select u.user_id,u.username,u.password");
        sql.append(",u.nickname,u.avatar,u.sex,u.phone");
		sql.append(",u.email,u.email_verified,u.real_name,u.id_card");
		sql.append(",u.birthday,u.introduction,u.organization_id,u.status");
		sql.append(",u.tenant_id,u.type,u.admin,u.state");
		sql.append(",u.customer_id,u.gzhId,u.create_time,u.create_user");
		sql.append(",u.update_time,u.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nickname createName ");
        sql.append(" from sys_user u ");
        sql.append(" inner join sys_user suser on suser.user_id=u.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=u.organization_id and sogzn.deleted=0 ");
        sql.append(" where u.deleted=0 and u.id=:id ");
        map.put("id", id);
        getMapParameter(sql, map);
        return jdbcTemplate.queryForObject(sql.toString(), map, rm);
    }

    @Override
    public Integer save(User user, User loginUser) {
        GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        KeyHolder keyHolder = new GeneratedKeyHolder();
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql =new StringBuffer("insert into sys_user (");
        sql.append("user_id,username,password,origin_password,nickname,customer_id");
		sql.append(",avatar,sex,phone,email");
		sql.append(",email_verified,real_name,id_card,birthday");
		sql.append(",introduction,organization_id,status,tenant_id");
		sql.append(",type,admin,state");
		sql.append(",gzhId,create_user,create_time) values ( ");
        sql.append(":user_id,:username,:password,:origin_password,:nickname,:customer_id");
		sql.append(",:avatar,:sex,:phone,:email");
		sql.append(",:email_verified,:real_name,:id_card,:birthday");
		sql.append(",:introduction,:organization_id,:status,:tenant_id");
		sql.append(",:type,:admin,:state");
		sql.append(",:gzhId,:create_user,now())");
        map.put("user_id", user.getUserId()==null?null:user.getUserId()+"");
        map.put("username", user.getUsername());
        map.put("password", user.getPassword());
        map.put("origin_password", user.getOriginPassword());
        map.put("nickname", user.getNickname());
        map.put("customer_id", user.getCustomerId());
        map.put("avatar", user.getAvatar());
        map.put("sex", user.getSex()==null?null:user.getSex()+"");
        map.put("phone", user.getPhone());
        map.put("email", user.getEmail());
        map.put("email_verified", user.getEmailVerified()==null?null:user.getEmailVerified()+"");
        map.put("real_name", user.getRealName());
        map.put("id_card", user.getIdCard());
        map.put("birthday", user.getBirthday() == null? null: DateUtil.formatDate(user.getBirthday()));
        map.put("introduction", user.getIntroduction());
        map.put("organization_id", loginUser.getOrganizationId() + "");
        map.put("status", user.getStatus()==null?"0":user.getStatus()+"");
        map.put("tenant_id", user.getTenantId()==null?"2":user.getTenantId()+"");
        map.put("type", user.getType());
        map.put("admin", user.getAdmin());
        map.put("state", user.getState()==null?"0":user.getState()+"");
        map.put("gzhId", user.getGzhId()+"");
        map.put("create_user", loginUser.getUserId() + "");
        getMapParameter(sql, map);
        int retVal = this.jdbcTemplate.update(sql.toString(), new SqlParameterSource() {
            @Override
            public boolean hasValue(String paramName) {
                return map.containsKey(paramName);
            }

            @Override
            public Object getValue(String paramName) throws IllegalArgumentException {
                return map.get(paramName);
            }
        }, generatedKeyHolder);

        Integer id = generatedKeyHolder.getKey().intValue();
        return id;
    }

    @Override
    public boolean update(User user, User loginUser) {
        Map<String, String> map  = new HashMap<String, String>();
        StringBuffer sql =new StringBuffer("update sys_user set ");
		sql.append(",nickname=:nickname,avatar=:avatar,sex=:sex ");
		sql.append(",phone=:phone,email=:email,email_verified=:email_verified ");
		sql.append(",real_name=:real_name,id_card=:id_card,birthday=:birthday ");
		sql.append(",introduction=:introduction,status=:status,tenant_id=:tenant_id ");
		sql.append(",type=:type,admin=:admin,state=:state ");
		sql.append(",customer_id=:customer_id,gzhId=:gzhId,update_time=now() ");
		sql.append(",update_user=:update_user where user_id=:user_id ");
        map.put("nickname", user.getNickname());
        map.put("avatar", user.getAvatar());
        map.put("sex", user.getSex()==null?null:user.getSex()+"");
        map.put("phone", user.getPhone());
        map.put("email", user.getEmail());
        map.put("email_verified", user.getEmailVerified()==null?null:user.getEmailVerified()+"");
        map.put("real_name", user.getRealName());
        map.put("id_card", user.getIdCard());
        map.put("birthday", DateUtil.formatDate(user.getBirthday()));
        map.put("introduction", user.getIntroduction());
        map.put("status", user.getStatus()==null?null:user.getStatus()+"");
        map.put("tenant_id", user.getTenantId()==null?null:user.getTenantId()+"");
        map.put("type", user.getType());
        map.put("admin", user.getAdmin());
        map.put("state", user.getState()==null?null:user.getState()+"");
        map.put("customer_id", user.getCustomerId());
        map.put("gzhId", user.getGzhId()+"");
        map.put("update_user", loginUser.getUserId() + "");
        map.put("user_id", user.getUserId()+"");
        getMapParameter(sql, map);
        int count = jdbcTemplate.update(sql.toString(), map);
        return count > 0;
    }

    @Override
    public boolean updateGzhId(User user) {
        Map<String, String> map  = new HashMap<String, String>();
        StringBuffer sql =new StringBuffer("update sys_user set ");
		sql.append("gzhId=:gzhId,update_time=now() ");
		sql.append(" where user_id=:user_id ");
        map.put("gzhId", user.getGzhId()+"");
        map.put("user_id", user.getUserId()+"");
        getMapParameter(sql, map);
        int count = jdbcTemplate.update(sql.toString(), map);
        return count > 0;
    }

    @Override
    public boolean remove(String id, User loginUser) {
        int count = 0;
        Map<String, String> map = null;
        if(id.length()>0){
            for(String id1 : id.split(",")){
                map  = new HashMap<String, String>();
                if(id1==null || id1.equals("")){ break; }
                StringBuffer sql =new StringBuffer("update sys_user set deleted=1" +
                    ",update_user=:update_user, update_time=now() "
                    + " where user_id =:user_id ");
                map.put("update_user", loginUser.getUserId() + "");
                map.put("user_id", id1);
                getMapParameter(sql, map);
                count = jdbcTemplate.update(sql.toString(),map);
            }
        }
        return count > 0;
    }
}
